package com.bobi.tfca.ui.mainnavigation.message.chatroom

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentGroupchatRoomBinding
import com.bobi.tfca.model.Callback
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.model.MsgType
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.ui.adapter.MessageAdapter
import com.bobi.tfca.util.LogUtil
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


class ChatRoomFragment : BaseFragment<FragmentGroupchatRoomBinding, ChatRoomFragmentVM>(
    FragmentGroupchatRoomBinding::inflate,
    ChatRoomFragmentVM::class.java,
    true
) {
    // 消息聊天块
    private lateinit var messageRV: RecyclerView
    // 编辑消息
    private lateinit var etMessage: EditText

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentGroupchatRoomBinding,
        viewModel: ChatRoomFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        val groupName = publicViewModel!!.chatRoom.value!!.groupName

        // 设置头部菜单的按钮
        setTopPanelStyle(binding, groupName)

        // 初始化RV
        initRecyclerView(binding)

        // 初始化发送信息
        initSendMessage(binding)

        viewModel!!.apply {
            // 设置历史消息监听
            messages.observe(viewLifecycleOwner) {
                val adapter = messageRV.adapter as MessageAdapter
                adapter.setItemList(it)
                adapter.notifyDataSetChanged()
                // 滑动到最后一个位置
                val lastItemPosition = adapter.itemCount - 1
                if (lastItemPosition >= 0) {
                    messageRV.scrollToPosition(lastItemPosition)
                }
            }
        }

        publicViewModel!!.apply {
            chatRoom.observe(viewLifecycleOwner) {
                binding.topPanel.titleText.text = it.groupName
            }
        }

        // 检查Socket连接
        if (AppCache.getService() != null) {
            // 收信息显示
            AppCache.getService().setReceiveMsgCallback(receiveMsgCallback)
            val connect = AppCache.checkSocketConnectStatus()
            if (!connect) {
                AppCache.getService()
                    .login() { code: Int, msg: String, aVoid: Void? ->
                    }
            }
        }
    }


    /**
     * 初始化发送信息
     * 方案是：初始化fragment时，先查询数据库得到历史消息，再设置收信息和发信息的处理
     * 初始化的监听跟在线收发信息不影响
     */
    private fun initSendMessage(binding: FragmentGroupchatRoomBinding) {
        // 发送信息文本
        etMessage = binding.chatContent
        // 设置发送按钮点击事件
        val chatSubmit = binding.chatSubmit
        chatSubmit.setOnClickListener {
            if (etMessage.length() == 0) {
                Toast.makeText(requireContext(), "发送内容为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val connect = AppCache.checkSocketConnectStatus()
            if (connect) {
                val myAccount = AppCache.getMyInfo()
                val messageResponse = MessageResponse()
                messageResponse.senderId = myAccount.memberId
                messageResponse.receiverId = 0
                messageResponse.contentType = MsgType.TEXT
                messageResponse.content = etMessage.text.toString()
                messageResponse.groupId = publicViewModel!!.chatRoom.value!!.groupId
                messageResponse.senderName = myAccount.memberName
                messageResponse.senderPicture = myAccount.picture
                AppCache.getService()
                    .sendMsg(messageResponse) { code: Int, msg: String, aVoid: Void? ->
                        if (code == 200) {
                            etMessage.text = null
                            val adapter = messageRV.adapter as MessageAdapter
                            adapter.messageResponseList.add(messageResponse)
                            adapter.notifyItemInserted(adapter.getItemCount() - 1)
                            // 滑动到最后一个位置
                            val lastItemPosition = adapter.itemCount - 1
                            if (lastItemPosition >= 0) {
                                messageRV.smoothScrollToPosition(lastItemPosition)
                            }
                        } else {
                            Toast.makeText(
                                requireContext(),
                                "[发送失败]" + messageResponse.content + "," + msg,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
            } else {
                AppCache.getService()
                    .login() { code: Int, msg: String, aVoid: Void? ->
                    }
                Toast.makeText(requireActivity(), "Socket未连接成功，请稍后重试", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(binding: FragmentGroupchatRoomBinding) {
        // 初始化RV
        messageRV = binding.messageRV
        // 设置布局排列方式，默认垂直排列
        val linearLayoutManager = LinearLayoutManager(binding.root.context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        messageRV.layoutManager = linearLayoutManager
        // 添加分隔线
//        messageRV.addItemDecoration(
//            DividerItemDecoration(
//                binding.root.context,
//                LinearLayoutManager.VERTICAL
//            )
//        )
        // 绑定adapter
        val memberId = AppCache.getMyInfo().memberId
        val messageAdapter = MessageAdapter(this, memberId, arrayListOf())
        messageRV.adapter = messageAdapter
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(
        binding: FragmentGroupchatRoomBinding,
        groupName: String
    ) {
        val topPanel = binding.topPanel
        val leftLayout = topPanel.leftLayout
        leftLayout.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav)
                .navigate(R.id.action_groupchatRoomFragment_to_groupDetailFragment)
        }
        val title = topPanel.titleText
        // 群聊名称
        title.text = groupName
    }

    /**
     * 收信息显示
     */
    private val receiveMsgCallback =
        Callback<MessageResponse> { code, msg, message ->
            // 可能线程不安全
            val adapter = messageRV.adapter as MessageAdapter
            adapter.messageResponseList.add(message)
            Log.i("RECEIVING", message.content)
            adapter.notifyItemInserted(adapter.getItemCount() - 1)
            // 滑动到最后一个位置
            val lastItemPosition = adapter.itemCount - 1
            if (lastItemPosition >= 0) {
                messageRV.smoothScrollToPosition(lastItemPosition)
            }
            // 将消息状态设置为已读
            updateGroupMessageRead(message.messageId)
        }

    private fun updateGroupMessageRead(messageId: Long) {
        LogUtil.i("更新消息状态-----")
        publicViewModel!!.apply {
            request(MessageAPI::class.java).updateGroupMessageRead(messageId).getResponse {
                it.collect{
                    when(it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }
                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                        }
                    }
                }
            }
        }
    }

    override fun resumeFragment(viewModel: ChatRoomFragmentVM?) {
        super.resumeFragment(viewModel)

        // 请求历史消息
        val groupId = publicViewModel!!.chatRoom.value!!.groupId
        viewModel!!.getHistoryMessages(groupId, publicViewModel)

        val connect = AppCache.checkSocketConnectStatus()
        if (!connect) {
            AppCache.getService()
                .login() { code: Int, msg: String, aVoid: Void? ->
                    if (code == 200) {
                        Toast.makeText(
                            requireContext(),
                            "登录成功",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        AppCache.getService().setReceiveMsgCallback(null)
    }
}